package com.heima.app.filter;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.heima.app.util.AppJwtUtil;

/**
 * 网关用户认证过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求实例
        ServerHttpRequest request = exchange.getRequest();

        //2.获取响应实例
        ServerHttpResponse response = exchange.getResponse();

        //3.获取请求路径
        String path = request.getURI().getPath();

        //4.判断如果是登录路径，则放行
        if(path.startsWith("/user/api/v1/login/login_auth")){
            return chain.filter(exchange);
        }

        //5.从请求头获取token
        String token = request.getHeaders().getFirst("token");

        //6.判断如果token无值，则响应401
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claimsBody);
            //7.如果成功，则在header中设置userId，放行
            if(result==-1 || result==0){
                String userId = String.valueOf(claimsBody.get("id"));
                request.mutate().header("userId", userId); //将用户id设置到header，方便后续微服务中随时取用用户ID
                return chain.filter(exchange);
            } else {
                //8.解析token，如果token解析失败，则响应401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //9.如果解析token抛异常，则响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

    }

    @Override
    public int getOrder() {
        return 0;//值越小，优先级越高，越先被执行人
    }
}
